package com.dianxin.smartpark.service.common.impl;

import java.util.Date;
import java.util.List;

import com.chinatelecom.response.common.CommonResponseBody;
import com.chinatelecom.response.utils.BeanUtil;
import com.chinatelecom.response.utils.Convert;
import com.chinatelecom.response.utils.ResponseBodyWrapperUtil;
import com.chinatelecom.response.constant.ErrMsgEnum;

import com.chinatelecom.response.utils.StringUtils;
import com.dianxin.acl.api.dto.SsoUserDTO;
import com.dianxin.smartpark.dao.dataobject.common.SmartParkCard;
import com.dianxin.smartpark.dao.dataobject.common.SmartParkCardExample;
import com.dianxin.smartpark.dao.mapper.common.SmartParkCardMapper;
import com.dianxin.smartpark.dao.qo.common.SmartParkCardQO;
import com.dianxin.smartpark.service.common.SmartParkCardService;
import com.dianxin.smartpark.service.common.SmartParkDeviceAuthService;
import com.dianxin.smartpark.service.common.SmartParkUserConfigService;
import com.dianxin.smartpark.service.config.MqttOptType;
import com.dianxin.smartpark.service.vo.common.SmartParkCardVO;
import com.dianxin.sso.client.context.UserHolderContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 卡务管理业务层处理
 * 
 * @author chenjiasong
 * @date 2021-07-28
 */
@Service
public class SmartParkCardServiceImpl implements SmartParkCardService
{
    private final static Logger logger = LoggerFactory.getLogger(SmartParkCardServiceImpl.class);
    @Resource
    private SmartParkCardMapper smartParkCardMapper;

    @Resource
    private SmartParkDeviceAuthService smartParkDeviceAuthService;

    /**
     * 查询卡务管理
     * 
     * @param qo 卡务管理ID
     * @return 卡务管理
     */
    @Override
    public CommonResponseBody<SmartParkCardVO> selectSmartParkCard(SmartParkCardQO qo)
    {
        if(StringUtils.isNull(qo.getId()) && StringUtils.isNull(qo.getCardNum())){
            return ResponseBodyWrapperUtil.fail(ErrMsgEnum.ERROR_PARAME);
        }
        SmartParkCardExample smartParkCardExample = new SmartParkCardExample();
        SmartParkCardExample.Criteria criteria = smartParkCardExample.createCriteria();
        if (qo.getTenantId() != null) {
            criteria.andTenantIdEqualTo(qo.getTenantId());
        }
        if (qo.getCardNum() != null) {
            criteria.andCardNumEqualTo(qo.getCardNum());
        }
        if (qo.getId() != null) {
            criteria.andIdEqualTo(qo.getId());
        }
        criteria.andIsDeletedEqualTo(0);
        List<SmartParkCard> passRecords = smartParkCardMapper.selectByExample(smartParkCardExample);
        return ResponseBodyWrapperUtil.successWrapper(StringUtils.isNotEmpty(passRecords)?passRecords.get(0):null,SmartParkCardVO.class);
    }

    /**
     * 查询卡务管理列表
     * 
     * @param qo 卡务管理
     * @return 卡务管理
     */
    @Override
    public CommonResponseBody<List<SmartParkCardVO>> selectSmartParkCardList(SmartParkCardQO qo)
    {
        SmartParkCardExample smartParkCardExample = new SmartParkCardExample();
        SmartParkCardExample.Criteria criteria = smartParkCardExample.createCriteria();
        if (qo.getTenantId() != null) {
            criteria.andTenantIdEqualTo(qo.getTenantId());
        }
        if (qo.getUserId() != null) {
            criteria.andUserIdEqualTo(qo.getUserId());
        }

        if (qo.getUserType() != null) {
            criteria.andUserTypeEqualTo(qo.getUserType());
        }

        if (qo.getStatus() != null) {
            criteria.andStatusEqualTo(qo.getStatus());
        }

        if (qo.getCardNum() != null) {
            criteria.andCardNumLike(qo.getCardNum()+"%");
        }

        criteria.andIsDeletedEqualTo(0);
        if (qo.getNeedPage()) {
            smartParkCardExample.setOrderByClause("gmt_create desc limit " + (qo.getPageIndex() - 1) * qo.getPageSize() + "," + qo.getPageSize());
        } else {
            smartParkCardExample.setOrderByClause("gmt_create desc");
        }
        List<SmartParkCard> passRecords = smartParkCardMapper.selectByExample(smartParkCardExample);
        long count = smartParkCardMapper.countByExample(smartParkCardExample);
        return ResponseBodyWrapperUtil
                .successListWrapper(passRecords, count, qo, SmartParkCardVO.class);
    }

    /**
     * 新增卡务管理
     * 
     * @param vo 卡务管理
     * @return 结果
     */
    @Override
    public CommonResponseBody<Boolean> insertSmartParkCard(SmartParkCardVO vo)
    {
        // 验证 todo
        SmartParkCard smartParkCard = new SmartParkCard();
        try {
            BeanUtil.insertConversion(vo, smartParkCard);
        } catch (Exception e) {
            logger.error("", e);
        }
        SsoUserDTO ssoUserDTO = UserHolderContext.getUser();
        smartParkCard.setGmtCreateName(ssoUserDTO!=null?ssoUserDTO.getRealName():"");
        smartParkCard.beforeInsert();
        int res = 0;
        if(StringUtils.isNotEmpty(vo.getCardNums())){
            String[] cardNums = vo.getCardNums().split(",");
            for (String cardNum: cardNums) {
                smartParkCard.setCardNum(cardNum);
                res = smartParkCardMapper.insertSelective(smartParkCard);
            }
        }else {
            res = smartParkCardMapper.insertSelective(smartParkCard);
        }
        return ResponseBodyWrapperUtil.toResData(res);
    }

    /**
     * 修改卡务管理
     * 
     * @param vo 卡务管理
     * @return 结果
     */
    @Override
    public CommonResponseBody<Boolean> updateSmartParkCard(SmartParkCardVO vo) throws Exception {
        // 验证 todo
        SmartParkCard smartParkCard = new SmartParkCard();
        try {
            BeanUtil.insertConversion(vo, smartParkCard);
        } catch (Exception e) {
            logger.error("", e);
        }
        smartParkCard.beforeUpdate();
        SmartParkCard smartParkCard2  = smartParkCardMapper.selectByPrimaryKey(smartParkCard.getId());
        if(smartParkCard.getStatus()==1){
            if(StringUtils.isNull(smartParkCard.getUserId())){
                smartParkCard.setUserId(smartParkCard2.getUserId());
            }
            smartParkCard.setIssueTime(new Date());
        }
        smartParkCardMapper.updateByPrimaryKeySelective(smartParkCard);

        //判断是否发行给人
        if(smartParkCard.getStatus()==1 && StringUtils.isNotNull(smartParkCard.getUserId())){
            smartParkDeviceAuthService.sendUserDeviceAuth(Convert.toStr(smartParkCard.getUserId()),MqttOptType.ADDUSERCARD.getOptCode(),smartParkCard2.getCardNum());
        }else if(smartParkCard2.getStatus()==1 && smartParkCard.getStatus()!=1){
            smartParkDeviceAuthService.sendUserDeviceDelAuth(Convert.toStr(smartParkCard2.getUserId()),MqttOptType.DELUSERCARD.getOptCode(),smartParkCard2.getCardNum());
        }
        return ResponseBodyWrapperUtil.success();
    }

    /**
     * 删除卡务管理信息
     * 
     * @param vo 卡务管理
     * @return 结果08
     */
    @Override
    public CommonResponseBody<Boolean> deleteSmartParkCard(SmartParkCardVO vo)
    {
        // 验证 todo
        if(StringUtils.isNotEmpty(vo.getIds())){
            if(vo.getIds().split(",").length<=0){
                return ResponseBodyWrapperUtil.fail(ErrMsgEnum.ERROR_PARAME);
            }
        }else {
            return ResponseBodyWrapperUtil.fail(ErrMsgEnum.ERROR_PARAME);
        }
        SmartParkCard smartParkCard = new SmartParkCard();
        try {
            BeanUtil.insertConversion(vo, smartParkCard);
        } catch (Exception e) {
            logger.error("", e);
        }
        smartParkCard.beforeDelete();
        smartParkCard.setIds(Convert.toLongArray(vo.getIds()));
        return ResponseBodyWrapperUtil.toResData(smartParkCardMapper.updateByPrimaryKeySelective(smartParkCard));
    }
}
